<template>
  <view class="product-page">
    <!-- 头部区域 -->
    <view class="fix-top" :style="{ top: dynamicTop }">
      <view class="btn-icon" @click="clickIcon">
        <uni-icons type="bars" color="#fff"></uni-icons>
      </view>
      <view class="content" v-if="isShowFix">
        <view class="header">
          <view class="header-select">
            <uni-data-select
              v-model="selectData.categoryId"
              :localdata="categoryList"
              @change="selectChange"></uni-data-select>
          </view>
          <uni-easyinput
            class="header-input"
            suffixIcon="search"
            v-model="selectData.name"
            placeholder="搜索商品名称"
            @iconClick="inputClick"></uni-easyinput>
        </view>
        <view class="header-btn" @click="handleAddProduct">添加商品</view>
      </view>
    </view>

    <!-- 产品列表区域 -->
    <scroll-view
      class="scroll-body"
      scroll-y="true"
      refresher-enabled="true"
      :refresher-threshold="100"
      :refresher-triggered="loadingStatus"
      refresher-background="#ddd"
      @refresherrefresh="onRefresh">
      <view class="product-list">
        <uni-list
          class="list-body"
          v-if="productList && productList.length > 0">
          <uni-list-item v-for="(item, index) in productList" :key="index">
            <template v-slot:body>
              <view class="product-item">
                <view class="item-top">
                  <image
                    class="item-top-img"
                    :src="completeImgPath(item.mainImage)"></image>
                </view>
                <view class="item-bottom">
                  <view class="top">
                    <view class="name">
                      {{ item.name }}
                    </view>
                    <view class="status">
                      <uni-tag
                        :type="item.status == 'on_sale' ? 'success' : 'error'"
                        :text="item.statusName"></uni-tag>
                    </view>
                    <view>
                      <uni-tag
                        type="primary"
                        :text="item.categoryName"></uni-tag>
                    </view>
                  </view>
                  <view class="middle">
                    <text class="sellingPrice">￥{{ item.sellingPrice }}</text>
                    <!-- <text class="originalPrice">
                      ￥{{ item.originalPrice }}
                    </text> -->
                  </view>
                  <view class="bottom">
                    <view class="btn" @click="handleEdit(item)">编辑</view>
                    <view
                      class="btn btn-delete"
                      @click="handleDelete(item._id)">
                      删除
                    </view>
                  </view>
                </view>
              </view>
            </template>
          </uni-list-item>
        </uni-list>
        <view class="no-list" v-else>暂无商品</view>
      </view>
    </scroll-view>
    <uni-pagination
      v-if="productList && productList.length > 0"
      :current="pageData.page"
      :total="pageData.total"
      :pageSize="pageData.pageSize"
      title="标题文字"
      prev-text="前一页"
      next-text="后一页"
      @change="pageChange" />

    <view
      class="container-form"
      v-if="isShowPopup"
      :style="{ top: dynamicTop }">
      <uni-forms
        ref="formRef"
        class="form-body"
        label-position="top"
        label-width="100"
        :rules="formRules"
        :modelValue="productData">
        <uni-forms-item label="商品名称" required name="name">
          <uni-easyinput
            v-model="productData.name"
            placeholder="请输入商品名称" />
        </uni-forms-item>
        <uni-forms-item label="商品分类" required name="categoryId">
          <uni-data-select
            placeholder="请选择商品分类"
            v-model="productData.categoryId"
            :localdata="categoryList"></uni-data-select>
        </uni-forms-item>

        <uni-forms-item label="商品状态" required name="status">
          <uni-data-select
            placeholder="请选择商品状态"
            v-model="productData.status"
            :localdata="statusList"></uni-data-select>
        </uni-forms-item>

        <uni-forms-item label="商品售价" required name="sellingPrice">
          <uni-number-box
            :min="1"
            :max="10000"
            v-model="productData.sellingPrice"></uni-number-box>
        </uni-forms-item>

        <!-- <uni-forms-item label="商品原价" required name="originalPrice">
          <uni-number-box
            :min="1"
            :max="10000"
            v-model="productData.originalPrice"></uni-number-box>
        </uni-forms-item> -->

        <uni-forms-item label="商品封面" required name="mainImage">
          <view class="form-item">
            <FileUploader
              v-model="productData.mainImage"
              title="上传商品封面"
              :limit="1"
              @upload-success="handleUploadSuccessMain" />
          </view>
        </uni-forms-item>

        <uni-forms-item label="商品详情图" required name="detailImages">
          <view class="form-item">
            <FileUploader
              v-model="productData.detailImages"
              title="上传商品详情图"
              :limit="5"
              @upload-success="handleUploadSuccessDetail" />
          </view>
        </uni-forms-item>

        <uni-forms-item label="商品简介" required name="description">
          <uni-easyinput
            v-model="productData.simpleDesc"
            placeholder="请输入商品简介" />
        </uni-forms-item>

        <uni-forms-item label="商品描述" required name="description">
          <uni-easyinput
            type="textarea"
            v-model="productData.description"
            class="custom-textarea"
            placeholder="请输入商品描述" />
        </uni-forms-item>

        <uni-forms-item label="商品特色" required name="features">
          <view v-if="productData.features && productData.features.length > 0">
            <view
              class="features-item"
              v-for="(elem, index) in productData.features"
              :key="index">
              <uni-easyinput
                v-model="productData.features[index]"
                style="margin-bottom: 10px"
                placeholder="请输入商品特色" />
              <uni-icons
                type="minus"
                size="32"
                style="margin-left: 5px; margin-bottom: 10px"
                color="#f00"
                @click="deleteFeature(index)"></uni-icons>
            </view>
          </view>

          <view class="add-feature-btn" @click="addFeature">
            <uni-icons type="plus" size="16" color="#666"></uni-icons>
            <text>添加特色</text>
          </view>
        </uni-forms-item>
        <uni-forms-item label="配料信息" required name="ingredients">
          <uni-easyinput
            type="textarea"
            class="custom-textarea"
            v-model="productData.ingredients"
            placeholder="请输入配料信息" />
        </uni-forms-item>
      </uni-forms>
      <view class="btn-group">
        <view class="btn" @click="handleCancel">取消</view>
        <view class="btn btn-save" @click="handleSave">保存</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import API from "@/api/index.js";
import { completeImgPath } from "@/utils/common.js";
import FileUploader from "./FileUploader.vue";

const loadingStatus = ref(false);
const onRefresh = async () => {
  console.log("onRefresh");
  loadingStatus.value = true;
  await getProductList();
};

const isShowFix = ref(false);
const clickIcon = () => {
  isShowFix.value = !isShowFix.value;
};
// 定义分类类型
interface SearchType {
  categoryId?: string;
  name?: string;
}
// 定义分类下拉类型
interface SelectType {
  value: string;
  text: string;
}

// 定义产品类型
interface ProductType {
  _id?: string;
  name: string;
  description: string;
  categoryId: string;
  categoryName?: string;
  status: string;
  statusName: string;
  sellingPrice?: number;
  originalPrice?: number;
  mainImage: string;
  detailImages?: string[];
  features?: string[];
  ingredients: string;
  simpleDesc?: string;
  isHot: boolean;
}

//搜索对象变量
const selectData = ref<SearchType>({
  categoryId: "",
  name: "",
});

const pageData = ref({
  page: 1,
  total: 0,
  pageSize: 3,
});

// 分类数据列表
const categoryList = ref<SelectType[]>([]);

//商品数据列表
const productList = ref<ProductType[]>([]);

//新增和编辑的变量
const isShowPopup = ref(false);
const isEdit = ref(false);
const productData = ref<ProductType>();
//初始化productData
const initProductData = () => {
  productData.value = {
    features: [""],
    mainImage: "",
    detailImages: [],
    name: "",
    description: "",
    categoryId: "",
    categoryName: "",
    sellingPrice: 0,
    originalPrice: 0,
    status: "",
    statusName: "",
    ingredients: "",
    simpleDesc: "",
    isHot: false,
  };
};
initProductData();

const statusList = ref([
  {
    value: "on_sale",
    text: "在售",
  },
  {
    value: "off_sale",
    text: "下架",
  },
]);

//表单验证规则
const formRules = {
  name: {
    rules: [
      {
        required: true,
        errorMessage: "商品名称不能为空",
      },
    ],
  },
  age: {
    rules: [
      {
        required: true,
        errorMessage: "年龄不能为空",
      },
    ],
  },
};

const deleteFeature = (index) => {
  productData.value.features.splice(index, 1);
};

const addFeature = () => {
  productData.value.features.push("");
};

onMounted(async () => {
  await getCategoryList();
  await getProductList();
});

//获取分类列表
const getCategoryList = async () => {
  const res = await API.category.getCategoryListApi({ isShow: true });
  if (res.success && res.data.items && res.data.items.length > 0) {
    categoryList.value = res.data.items.map((elem) => {
      return {
        value: elem._id,
        text: elem.classifyname,
      };
    });
  }
};

//获取商品列表
const getProductList = async () => {
  //重置数据
  productList.value = [];

  let params: any = {
    page: pageData.value.page,
    pageSize: pageData.value.pageSize,
  };
  if (selectData.value.categoryId) {
    params.categoryId = selectData.value.categoryId;
  }
  if (selectData.value.name) {
    params.name = selectData.value.name;
  }

  const res = await API.product.getProductListApi(params);
  if (res.success && res.data.items && res.data.items.length > 0) {
    productList.value = res.data.items;
    pageData.value.total = res.data.meta.totalItems;
  }
  loadingStatus.value = false;
};

//下拉选择
const selectChange = async () => {
  pageData.value.page = 1;
  await getProductList();
};
//输入搜索
const inputClick = async () => {
  pageData.value.page = 1;
  await getProductList();
};
//页码修改
const pageChange = async (e) => {
  pageData.value.page = e.current;
  await getProductList();
};

// 处理编辑
const handleEdit = (data: ProductType) => {
  isEdit.value = true;
  productData.value = data;
  isShowPopup.value = true;
};

// 处理删除
const handleDelete = (id: string) => {
  console.log("id", id);
  uni.showModal({
    title: "删除",
    content: "确定删除当前商品",
    success: async (res) => {
      if (res.confirm) {
        // 用户点击了确定按钮，执行跳转等操作
        console.log("用户点击确定,id=", id);
        const res = await API.product.deleteProductInfoByIdApi(id);
        if (res.success) {
          await getProductList();
        }
      } else if (res.cancel) {
        // 用户点击了取消按钮，执行相应操作
        console.log("用户点击取消");
      }
    },
  });
};

// 处理添加分类按钮点击
const handleAddProduct = () => {
  isEdit.value = false;
  isShowPopup.value = true;
  initProductData();
};

const handleCancel = () => {
  isShowPopup.value = false;
};

const handleSave = async () => {
  if (isEdit.value) {
    const res = await API.product.updateProductInfoByIdApi(
      productData.value._id,
      productData.value
    );
    if (res.success) {
      uni.showToast({
        title: "编辑成功",
        icon: "success",
      });
      isShowPopup.value = false;
      await getProductList();
    }
  } else {
    const res = await API.product.createProductApi(productData.value);
    if (res.success) {
      uni.showToast({
        title: "创建成功",
        icon: "success",
      });
      isShowPopup.value = false;
      await getProductList();
    }
  }
};

// 上传成功回调
const handleUploadSuccessMain = (urls: string[]) => {
  productData.value.mainImage = urls[0] ?? "";
};

// 上传成功回调
const handleUploadSuccessDetail = (urls: string[]) => {
  productData.value.detailImages = urls;
};

const dynamicTop = ref("");
const systemInfo = uni.getSystemInfoSync();
const statusBarHeight = systemInfo.statusBarHeight;
if (statusBarHeight > 0) {
  dynamicTop.value = "-1rpx";
} else {
  dynamicTop.value = "44px";
}
</script>

<style lang="scss" scoped>
.product-page {
  padding: 0px 16px 10px 16px;
  background-color: #fff8f0;
  position: relative;
  .fix-top {
    z-index: 1;
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    .btn-icon {
      background-color: #ff8a3c;
      width: 40px;
      height: 40px;
      margin: 10px;
      border-radius: 20px;
      text-align: center;
      line-height: 40px;
    }
    .content {
      background-color: #fff8f0;
      padding: 10px;
    }
  }
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    .header-select {
      width: 30%;
      margin-right: 5px;
    }
  }
  .header-btn {
    padding: 10px 10px;
    background-color: #ff8a3c;
    border-radius: 5px;
    color: #fff;
    text-align: center;
  }

  .scroll-body {
    height: 100%;
  }

  .product-list {
    // margin-top: 100px;
    .no-list {
      width: 100%;
      height: 200px;
      border: 1px dashed #aaa;
      line-height: 200px;
      text-align: center;
    }
    .list-body {
      background-color: #fff8f0;
    }
    .uni-list-item {
      margin-bottom: 10px;
    }
    .product-item {
      border-bottom: 1px solid #f5f5f5;
      margin: 5px 0px;
      margin: 10px 0px;
      display: flex;
      flex-direction: column;
      width: 100%;
      .item-top {
        width: 100%;
        .item-top-img {
          width: 100%;
          height: 200px;
        }
      }

      .item-bottom {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: start;
        justify-content: space-between;
        .top {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .name {
            font-size: 24px;
            font-weight: 700;
            margin-right: 10px;
            color: #5d4037;
          }
          .status {
            margin-right: 10px;
          }
          .type {
          }
        }
        .middle {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-top: 5px;
          .sellingPrice {
            font-size: 20px;
            font-weight: 700;
            color: #ff8a3c;
            margin-right: 10px;
          }
          .originalPrice {
            font-size: 14px;
            text-decoration: line-through;
            /* 可选：自定义删除线颜色和样式 */
            text-decoration-color: #000000; /* 红色删除线 */
            text-decoration-style: solid; /* 虚线删除线 */
          }
        }
        .bottom {
          width: 100%;
          margin-top: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          .btn {
            padding: 5px 30px;
            border-radius: 5px;
            color: #fff;
            background-color: #ff8a3c;
          }
          .btn-delete {
            background-color: #f00;
            margin-left: 30px;
          }
        }
      }
    }
  }

  .tip-text {
    font-size: 12px;
    color: #999;
    text-align: center;
    margin-top: 16px;
  }
  .product-popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;

    .popup-content {
      width: 90%;
      max-width: 400px;
      background-color: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

      .title {
        font-size: 18px;
        font-weight: bold;
        color: #333;
        margin-bottom: 20px;
        display: block;
      }

      .form-item {
        margin-bottom: 20px;
        .label {
          font-size: 14px;
          color: #666;
          margin-bottom: 8px;
          display: block;
        }

        .input {
          width: 100%;
          border-radius: 4px;
          font-size: 14px;
        }
        .checkbox {
          font-size: 14px;
        }
      }

      .btn-group {
        display: flex;
        justify-content: end;
        gap: 10px;

        .btn {
          padding: 5px 10px;
          border-radius: 5px;
          border: 1px solid #ddd;
        }
        .btn-save {
          color: #fff;
          background-color: #ff8a3c;
        }
      }
    }
  }
  .container-form {
    position: fixed;
    top: 0px;
    left: 0px;
    z-index: 2;
    width: 100%;
    height: 100%;
    padding: 20px;
    background-color: #fff8f0;
    overflow-y: scroll;
    .form-body {
      width: 100%;
      height: calc(100% - 50px);
      // padding: 5px 5px;
      margin-bottom: 10px;
      border: 1px solid #eee;
    }

    .features-item {
      display: flex;
      align-items: center;
      .btn {
        left: 5px;
      }
    }
    .add-feature-btn {
      display: flex;
      align-items: center;
      color: #409eff;
      font-size: 14px;
      cursor: pointer;
      margin-top: 8px;

      uni-icons {
        margin-right: 6px;
      }
    }
    .btn-group {
      display: flex;
      justify-content: flex-end;
      gap: 10px;

      .btn {
        padding: 5px 10px;
        border-radius: 5px;
        border: 1px solid #ddd;
      }
      .btn-save {
        color: #fff;
        background-color: #ff8a3c;
      }
    }
    .custom-textarea {
      width: 100%;
      min-height: 200rpx;
      padding: 20rpx;
      border: 1px solid #eee;
      border-radius: 8rpx;
      font-size: 28rpx;
      // 确保输入时能正确显示换行
      white-space: pre-wrap;
      // 解决 iOS 上输入时内容被截断的问题
      word-wrap: break-word;
    }
  }
}
</style>
